package util;

import fs.Data;
import fs.EmailConfig;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

/**
 *
 * @author the_rub
 */
public class Email {

  private String username;
  private String password;
  private String to;
  private String subject;
  private String mensaje;
  private String[] files;
  private String[] shortFiles;

  public Email(String to, String subject, String mensaje, String[] files, String[] shortFiles) {
    initConfig();
    this.to = to;
    this.subject = subject;
    this.mensaje = mensaje;
    this.files = files;
    this.shortFiles = shortFiles;
  }

  private void initConfig() {
    try {
      EmailConfig config = (EmailConfig) Data.ReadFrom(Data.EMAIL_SETTINGS);
      username = config.Addr + "@gmail.com";
      password = config.Passwd;
    } catch (Exception e) {
      username = "clinica.senzu" + "@gmail.com";
      password = "love";
      System.out.printf("?loading default email settings\n");
    }
  }

  public void Send() throws MessagingException {
    Properties props = new Properties();

    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");

    Session session = Session.getInstance(
      props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
          return new PasswordAuthentication(username, password);
        }
      }
    );

    session.setDebug(false);

    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress(username));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));

    //sub
    message.setSubject(subject);

    //message
    BodyPart body = new MimeBodyPart();
    body.setText(mensaje);

    //attach
    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(body);

    BodyPart attachment;

    for (int i = 0; i < files.length; i++) {
      attachment = new MimeBodyPart();
      attachment.setDataHandler(new DataHandler(new FileDataSource(files[i])));
      attachment.setFileName(shortFiles[i]);
      multipart.addBodyPart(attachment);
    }

    message.setContent(multipart);
    Transport.send(message);
  }

}
